﻿using AutoMapper;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infastruucture;
using BasicData.Write.API.application.Command.Role;
using MediatR;

namespace BasicData.Write.API.application.CommandHandler.Role
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<RoleModel> roelRepo;
        private readonly IMapper mapper;

        public UpdateRoleCommandHandler(IBaseRepository<RoleModel> roelRepo, IMapper mapper)
        {
            this.roelRepo = roelRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<object>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> res = new ApiResult<object>();
            var role = roelRepo.GetByModel(request.RoleId);
            if (role == null)
            {
                res.Code = BaseEnums.Failed;
                res.Msg = "要修改的角色不存在";
                res.Data = 0;
                return Task.FromResult(res);
            }
            role = mapper.Map(request, role);
            int r = roelRepo.Update(role);
            if (r > 0)
            {
                res.Code = BaseEnums.Success; ;
                res.Msg = "修改成功";
                res.Data = r;
            }
            else
            {
                res.Code = BaseEnums.Failed;
                res.Msg = "修改失败";
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
